package com.IM.handler;
import com.IM.ImServer;
import com.IM.command.ChatCommand;
import com.IM.result.Result;
import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.internal.StringUtil;
import com.IM.commandType.ChatCommandType;

public class ChatHandler {
    public static void execute(ChannelHandlerContext cxt, TextWebSocketFrame text){
        try{
            ChatCommand chat = JSON.parseObject(text.text(), ChatCommand.class);
            switch (ChatCommandType.match(chat.getType())){
                case  CHAT_PRIVATE -> {             //私聊
                    if(StringUtil.isNullOrEmpty(chat.getTarget())){
                        cxt.channel().writeAndFlush(Result.fail("消息发送失败，请指定用户"));
                        return;
                    }else{
                        //取出对应的channel
                        Channel channel = ImServer.User.get(chat.getTarget());
                        //目标对象不存在或下线
                        if(null==channel||channel.isActive()){
                            cxt.channel().writeAndFlush(Result.fail("消息发送失败："+chat.getTarget()+"不在线"));
                        }else{
                            channel.writeAndFlush(Result.success("私聊消息"+chat.getNickName(), chat.getContext()));
                        }

                    }
                }
                case CHAT_GROUP ->
                        ImServer.group.writeAndFlush(Result.success("群聊消息：发送者——"+chat.getNickName(), chat.getContext()));
                default ->
                        cxt.channel().writeAndFlush(Result.fail("消息模式不支持"));

            }
        }catch (Exception e){
            cxt.channel().writeAndFlush(Result.fail("你的消息格式不对，请重新发送"));
        }
    }
}
